<template>
	<view class="friend-talk">
		<u-navbar :title="friendName" :safeAreaInsetTop="true" placeholder leftIconSize="30"
			titleStyle="{font-weight: bold;font-size: 40rpx;}" @leftClick="goBack">
			<view slot="right">
				<u-icon name="list-dot" size="30" @click="toDetails"></u-icon>
			</view>
		</u-navbar>
		<scroll-view scroll-y="true" :style="[scrollStyle]" :refresher-enabled="true" :refresher-triggered="triggered"
			@refresherrefresh="onRefresh" refresher-background="#f5f6f7" refresher-default-style="black"
			@scrolltolower="onLoadMore">
			<view class="msg-list">
				<view class="msg-item" v-for="(item, index) in msgList" :key="index">
					<!-- <view v-if="showTime(item.create_time, index)" class="tac">{{
            item.create_time
          }}</view> -->
					<view :class="['msg-content', talkInfo.todoType == '2' ? 'flex-ac' : '']">
						<image class="user-avatar" :src="item.avatar"></image>
						<view class="msg">
							<u--text :text="item.create_time"></u--text>
							<view class="album-box" v-if="talkInfo.todoType == 1">
								<!-- <image class="no-img" src="/static/logo.png"></image> -->
								<u-album :urls="[item.image]"></u-album>
							</view>
							<audioCmpt class="audio-box" v-if="talkInfo.todoType == 2" :audioSrc="item.sound">
							</audioCmpt>
						</view>
					</view>
					<!-- <view :class="['msg-content',item.form=='get'?'':'right',item.type=='audio'?'flex-ac':'']">
						<image class="user-avatar" :src="friendInfo.avatar" mode=""></image>
						<view class="msg">
							<u-album v-if="item.type=='image'" :urls="[item.content]"></u-album>
							<view class="text-box" v-if="item.type=='instruction'">{{item.content}}</view>
							<audioCmpt class="audio-box" v-if="item.type=='audio'" :audioSrc="item.content"></audioCmpt>
						</view>
					</view> -->
				</view>
			</view>
		</scroll-view>
		<view class="func-box">
			<swiper class="swiper" :indicator-dots="true">
				<swiper-item>
					<view class="func-list">
						<view class="item" @click="openCameraPup">
							<view class="img-box">
								<image class="image" src="/static/icon/camera.png" mode=""></image>
							</view>
							<text>远程拍照</text>
						</view>
						<view class="item" @click="showAcoustic">
							<view class="img-box">
								<image class="image" src="/static/icon/acoustic.png" mode=""></image>
							</view>
							<text>远程录音</text>
						</view>
						<view class="item" @click="showFence">
							<view class="img-box">
								<image class="image" src="/static/icon/fence.png" mode=""></image>
							</view>
							<text>电子围栏</text>
						</view>
						<view class="item" @click="remoteCall">
							<view class="img-box">
								<image class="image" src="/static/icon/phone.png" mode=""></image>
							</view>
							<text>远程喊话</text>
						</view>
					</view>
				</swiper-item>
				<swiper-item>
					<view class="func-list">
						<view class="item" @click="goToMap">
							<view class="img-box">
								<image class="image" src="/static/icon/street.png" mode=""></image>
							</view>
							<text>位置轨迹</text>
						</view>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<u-popup mode="bottom" :round="10" :show="choseCarmea" @close="closeChoseCarmea">
			<view class="chose-camera">
				<view v-if="talkInfo.todoType == 1">
					<view class="camera-btn before-item flex-ac-jcc" @click="takePhoto(1)">
						<u-icon name="camera" size="30" color="#fff"></u-icon>
						<view>前置摄像头拍照</view>
					</view>
					<view class="camera-btn flex-ac-jcc" @click="takePhoto(0)">
						<u-icon name="camera-fill" size="30" color="#fff"></u-icon>
						<view>后置摄像头拍照</view>
					</view>
				</view>
				<view v-else>
					<view class="camera-btn flex-ac-jcc" @click="takeAudio">
						<u-icon name="mic" size="30" color="#fff"></u-icon>
						<view>开始录音</view>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import audioCmpt from "@/components/audioCmpt/index.vue";
	import {
		remote_photosLists,
		remote_soundLists,
		checkRoom,
	} from "@/common/api/index.js";

	export default {
		data() {
			return {
				friend_updateId: "", //好友详情查询ID
				friendId: "",
				friendName: "",
				friendInfo: {},
				choseCarmea: false,
				msgList: [],
				talkInfo: {
					todoType: 1, // 1 拍照  2 录音
					carmeraList: [],
					audioList: [],
				},
				carmeraPageInfo: {
					page_no: 1,
					page_size: 20,
					count: 1,
				},
				audioPageInfo: {
					page_no: 1,
					page_size: 20,
					count: 1,
				},
				triggered: false, // 下拉是否激活
				requestTimer: null,
				lockFunc: false, // 功能禁用
				online: false, // 在线状态
				scrollTop: 0,
				// timeSecod: 0, //计算拍照市场   超过10秒没有反应就是拍照失败
				// index: 0
			};
		},
		components: {
			audioCmpt,
		},
		watch: {
			talkInfo: {
				handler(newValue, oldValue) {
					console.log("newValue", newValue);
					if (newValue.todoType == 1) {
						this.msgList = newValue.carmeraList;
					} else {
						this.msgList = newValue.audioList;
					}
				},
				deep: true,
			},
		},
		computed: {
			scrollStyle() {
				return {
					height: `calc(100vh - 260rpx - ${this.$store.state.globalData.bottomSafeHeight}px - ${this.$store.state.globalData.statusBarHeight}px - 44px)`,
					"box-sizing": "border-box",
				};
			},
			showTime() {
				return (time, index) => {
					if (index == 0) return true;
					let lastDate = new Date(this.msgList[index - 1].time).getTime();
					let nowDate = new Date(time).getTime();
					return nowDate - lastDate > 1000 * 60 * 5;
				};
			},
		},
		onLoad(query) {
			this.friend_updateId = query.friend_updateId; //好友详情查询ID
			this.friendId = query.friend_id;
			this.online = query.online;
			this.friendName = decodeURI(query.frind_name);
		},
		onShow() {
			this.friendInfo = this.$store.state.choseFriendInfo;
			this.get_remote_photosLists();
		},
		onExit() {
			uni.$off("refresh_photo");
			uni.$off("refresh_audio");
			uni.$off("linkTrtc");
			uni.$off("trtc_quit");
		},
		created() {
			let that = this;
			uni.$on("refresh_photo", (data) => {
				if (data.code == 1) {
					let id =
						that.talkInfo.carmeraList[that.talkInfo.carmeraList.length - 1].id;
					that.get_remote_photosLists(id);
					that.endTimer("拍照成功，请在最新列表中查看");
				}
			});

			uni.$on("refresh_audio", (data) => {
				if (data.code == 1) {
					let id = that.talkInfo.audioList[that.talkInfo.audioList.length - 1].id;
					that.get_remote_soundLists(id);
					that.endTimer("录音成功，请在最新列表中查看");
				}
			});

			uni.$on("linkTrtc", (res) => {
				console.log(res.data.roomId, "res.data.roomId");
				uni.$emit("trtc_linkTrtc", {
					roomId: res.data.roomId,
					event: () => {
						that.lockFunc = true;
						that.endTimer("远程喊话房间链接成功");
					},
				});
			});
			// 监听trtc 退出
			uni.$on("trtc_quit", (res) => {
				that.lockFunc = false;
			});
		},
		methods: {
			openCameraPup() {
				if (this.talkInfo.todoType == 2) {
					this.talkInfo.todoType = 1;
				} else {
					this.choseCarmea = true;
				}
			},
			async showAcoustic() {
				if (this.talkInfo.todoType == 1) {
					this.talkInfo.todoType = 2;
					if (this.talkInfo.audioList.length == 0) {
						await this.get_remote_soundLists();
					}
				} else {
					this.choseCarmea = true;
				}
			},
			showFence() {
				uni.navigateTo({
					url: "/pages/map/electronicFence?friend_id=" +
						this.friendId +
						"&frind_name=" +
						encodeURI(this.friendName),
				});
			},
			// 远程喊话
			async remoteCall() {
				let that = this;
				if (!this.online || this.online == "false") {
					uni.showToast({
						icon: "none",
						title: "该用户不在线，请换一个用户试试吧",
					});
					return;
				}
				if (that.lockFunc) {
					uni.showToast({
						icon: "none",
						title: "当前远程喊话操作中...",
					});
					return;
				}
				// 向用户发送创建房间通知
				let formData = {
					roomId: "room_" + that.friendId,
					user_id: that.friendId,
				};
				that.startTimer();
				let res = await checkRoom(formData);
				if (res.code == 1) {
					// 直接链接
					uni.$emit("trtc_linkTrtc", {
						roomId: res.data.RoomString,
						event: () => {
							that.lockFunc = true;
							that.endTimer("远程喊话房间链接成功");
						},
					});
				} else {
					that.showMsg(res.msg);
					let userId = that.$store.state.userInfo.id;
					that.$store.commit("publishMessage", {
						topic: `${userId}_${that.friendId}`,
						msg: JSON.stringify({
							todo: "takeTrtc",
							data: {
								send_user_id: userId,
							},
						}),
					});
				}
			},
			// 地理位置
			goToMap() {
				uni.navigateTo({
					url: "/pages/map?friend_id=" +
						this.friendId +
						"&frind_name=" +
						encodeURI(this.friendName),
				});
			},
			// 拍照
			async takePhoto(id) {
				if (!this.online || this.online == "false") {
					uni.showToast({
						icon: "none",
						title: "该用户不在线，请换一个用户试试吧",
					});
					return;
				}
				if (this.lockFunc) {
					uni.showToast({
						icon: "none",
						title: "当前远程喊话操作中，请结束后再尝试该功能",
					});
					return;
				}
				let userId = this.$store.state.userInfo.id;
				this.choseCarmea = false;
				this.startTimer();
				this.$store.commit("publishMessage", {
					topic: `${userId}_${this.friendId}`,
					msg: JSON.stringify({
						todo: "takePhoto",
						data: {
							cameraId: id,
							user_id: userId,
						},
					}),
				});
			},
			// 远程录音
			takeAudio() {
				if (!this.online || this.online == "false") {
					uni.showToast({
						icon: "none",
						title: "该用户不在线，请换一个用户试试吧",
					});
					return;
				}
				if (this.lockFunc) {
					uni.showToast({
						icon: "none",
						title: "当前远程喊话操作中，请结束后再尝试该功能",
					});
					return;
				}
				let userId = this.$store.state.userInfo.id;
				this.choseCarmea = false;
				this.startTimer();
				this.$store.commit("publishMessage", {
					topic: `${userId}_${this.friendId}`,
					msg: JSON.stringify({
						todo: "takeAudio",
						data: {
							user_id: userId,
						},
					}),
				});
			},
			//    获取远程拍照列表
			async get_remote_photosLists(id = "") {
				let res = await remote_photosLists({
					...this.carmeraPageInfo,
					id,
				});
				if (res.code == 1) {
					if (id) {
						this.talkInfo.carmeraList.unshift(res.data.lists[0]);
					} else {
						this.talkInfo.carmeraList = [
							...this.talkInfo.carmeraList,
							...res.data.lists,
						];
						if (this.carmeraPageInfo.page_no == 1) {
							setTimeout(() => {
								this.scrollTop = 100000;
							}, 500);
						}
					}
					this.carmeraPageInfo.count = res.data.count;
				} else {
					this.showMsg(res.msg);
				}
			},
			// 自定义下拉刷新被触发  获取上一页数据
			onRefresh() {
				this.triggered = true;
				// 重置页码
				if (this.talkInfo.todoType == 1) {
					this.carmeraPageInfo.page_no = 1;
					this.talkInfo.carmeraList = [];
					this.get_remote_photosLists();
				} else {
					this.audioPageInfo.page_no = 1;
					this.talkInfo.audioList = [];
					this.get_remote_soundLists();
				}
				// 模拟加载完成
				setTimeout(() => {
					this.triggered = false;
				}, 1500);
			},
			// 上划加载历史数据
			onLoadMore() {
				if (this.talkInfo.todoType == 1) {
					this.carmeraPageInfo.page_no += 1;
					this.get_remote_photosLists();
				} else {
					this.audioPageInfo.page_no += 1;
					this.get_remote_soundLists();
				}
			},
			//    获取远程录音列表
			async get_remote_soundLists(id) {
				let res = await remote_soundLists({
					...this.audioPageInfo,
					id,
				});
				if (res.code == 1) {
					if (id) {
						this.talkInfo.audioList.unshift(res.data.lists[0]);
					} else {
						this.talkInfo.audioList = [
							...this.talkInfo.audioList,
							...res.data.lists,
						];
					}
					this.carmeraPageInfo.count = res.data.count;
				} else {
					this.showMsg(res.msg);
				}
			},
			closeChoseCarmea() {
				this.choseCarmea = false;
			},
			toDetails() {
				uni.navigateTo({
					url: `/pages/friends/details?friend_updateId=${this.friend_updateId}`,
				});
			},
			startTimer() {
				let that = this;
				uni.showLoading({
					mask: true,
					title: "正在获取中...",
					complete: () => {
						if (that.requestTimer) clearTimeout(that.requestTimer);
						that.requestTimer = setTimeout(() => {
							uni.showToast({
								icon: "none",
								title: "获取资源失败，请检查用户在线状态，或对方资源设备正在占用",
							});
							uni.hideLoading();
						}, 30000);
					},
				});
			},
			endTimer(title) {
				let that = this;
				if (that.requestTimer) {
					clearTimeout(that.requestTimer);
					uni.hideLoading();
					uni.showToast({
						title: title,
						duration: 1000,
						position: "top",
						icon: "none",
					});
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	page {
		background: #c4c4c4;
		font-size: 32rpx;
	}

	.friend-talk {
		.msg-list {
			padding: 20rpx;

			.msg-item {
				margin-bottom: 40rpx;

				.right {
					flex-direction: row-reverse;
					align-items: center;
				}

				.msg-content {
					display: flex;

					.msg {
						width: 70%;
						margin: 0 20rpx;
						text-align: right;

						.album-box {
							position: relative;

							.no-img {
								width: 50rpx;
								height: 50rpx;
								position: absolute;
								top: 15rpx;
								left: 0;
								z-index: -1;
							}
						}

						.text-box {
							padding: 10rpx 20rpx;
							background-color: #fff;
							border-radius: 20rpx;
						}
					}

					.user-avatar {
						width: 80rpx;
						height: 80rpx;
					}

					.get-img {
						width: 180rpx;
						height: 220rpx;
						border-radius: 20rpx;
					}
				}
			}
		}

		.func-box {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100vw;
			height: 260rpx;
			padding: 0 40rpx;
			padding-top: 40rpx;
			margin-bottom: constant(safe-area-inset-bottom);
			/* 兼容 iOS<11.2 */
			margin-bottom: env(safe-area-inset-bottom);
			/* 兼容iOS>= 11.2 */
			box-sizing: border-box;
			background-color: #fff;
			z-index: 9;
			border-top: 1rpx solid #ccc;

			.swiper {
				height: 220rpx;
			}

			.func-list {
				display: flex;

				.item {
					width: 25%;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;

					.img-box {
						width: 80rpx;
						height: 80rpx;
						border-radius: 20rpx;
						background-color: #f60;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-bottom: 20rpx;

						image {
							width: 40rpx;
							height: 40rpx;
						}
					}
				}
			}
		}

		.chose-camera {
			padding: 20rpx;
			padding-bottom: 90rpx;

			.camera-btn {
				margin: 0 auto;
				width: 80%;
				background-color: #f60;
				color: #fff;
				height: 80rpx;
				border-radius: 40rpx;
				margin-bottom: 20rpx;

				&:last-child {
					margin-bottom: 0;
				}
			}

			.before-item {
				background-color: #ffa163;
			}
		}
	}
</style>